package com.lh.struts.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lh.jsp.urlparamEncoding.CharacterEncodingConstants;
import com.lh.log.log4j.LoggerImpl;
import com.lh.log.log4j.interfaces.Log;

/**
 ************************************************
 ** Module : 字符编码过滤
 ** Date: 2011-12-27  Time: 下午04:07:08 
 ** Author 李恒(liheng)
 ** (C) Copyright 2011 广州赢典信息科技有限公司
 ************************************************ 
 */
public class CharsetEncodingFilter2 implements Filter {
	private static  Log logger = new LoggerImpl(CharsetEncodingFilter2.class);
	private FilterConfig config = null;
    private String requestEncoding = CharacterEncodingConstants.IOS8859;
    private String responseEncoding = null;

	@Override
	public void destroy() {	
		if(null!=config){
			config=null;
		}
		if(null!=requestEncoding){
			requestEncoding=null;
		}
		if(null!=responseEncoding){
			responseEncoding=null;
		}
		logger.debug("字符编码过滤器销毁。");

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain fc) throws IOException, ServletException {
		   if(this.config == null){
	            return;
	        }
	        HttpServletRequest request = (HttpServletRequest)req;
	        HttpServletResponse response = (HttpServletResponse)res;

	        CharacterEncodingHttpServletRequestWrapper  mrequestw  = new CharacterEncodingHttpServletRequestWrapper(request,requestEncoding);
	        CharacterEncodingHttpServletResponseWrapper wresponsew = new CharacterEncodingHttpServletResponseWrapper(response,responseEncoding);
	        fc.doFilter(mrequestw,wresponsew);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.config = filterConfig;		
        this.requestEncoding = config.getInitParameter("RequestEncoding");
        this.responseEncoding = config.getInitParameter("ResponseEncoding");
        logger.debug("字符编码过滤器"+config.getFilterName()+"初始化。");
	}

}
